package genesis.familytree.server.modules.sys.web;

import genesis.familytree.server.common.Constants;
import genesis.familytree.server.common.JsonResult;
import genesis.familytree.server.common.exception.GenesisException;
import genesis.familytree.server.common.persistence.Page;
import genesis.familytree.server.common.security.SystemAuthorizingRealm.Principal;
import genesis.familytree.server.common.web.BaseAdminController;
import genesis.familytree.server.modules.common.entity.Param;
import genesis.familytree.server.modules.common.service.IParamService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Date;

/**
 * Created by Cheng on 2016/05/22.
 */
@Controller
@RequestMapping("${adminPath}/param")
public class ParamController extends BaseAdminController {

    @Resource private IParamService paramService;

    /**
     * 后台用户管理主页
     * @return
     */
    @RequiresPermissions("sys:param:view")
    @RequestMapping("/index")
    public Object index() {
        return "redirect:/" + adminPath + "/param/list";
    }

    /**
     * 查看后台用户
     * @return
     */
    @RequiresPermissions("sys:param:view")
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public Object viewList() {
        return "/modules/sys/Param/Param_list";
    }

    @ResponseBody
    @RequiresPermissions("sys:param:view")
    @RequestMapping(value = "/list", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object getList(@RequestParam("page") int pageNumber) {
        JsonResult result = JsonResult.create();

        int pageSize = Constants.System.DEFAULT_PAGE_SIZE;
        //pageSize = 1;
        Page<Param> list = this.paramService.getPage(pageNumber, pageSize, new Param());

        result.success("data", list);

        return result;
    }

    @RequiresPermissions("sys:param:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public Object viewCreate(Model model) {

        Param entity = new Param();
        entity.setIsSystem(0);

        model.addAttribute("entity", entity);
        return "/modules/sys/Param/Param_edit";
    }

    @ResponseBody
    @RequiresPermissions("sys:param:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object create(@Valid Param param,
                         BindingResult bindingResult,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }
            if (!beanValidator(result, bindingResult)) {
                return result;
            }

            Date now = new Date();

            int userId = Principal.getCurrent().getId();
            param.setId(null);
            param.setCreateBy(userId);
            param.setCreateDate(now);
            this.paramService.saveOne(param);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }

    @RequiresPermissions("sys:param:edit")
    @RequestMapping(value = "/update", method = RequestMethod.GET)
    public Object viewUpdate(@RequestParam("id") int paramId,
                             Model model) {

        Param byId = this.paramService.getById(paramId);

        model.addAttribute("entity", byId);

        return "/modules/sys/Param/Param_edit";
    }

    @ResponseBody
    @RequiresPermissions("sys:param:edit")
    @RequestMapping(value = "/update", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object update(@Valid Param param,
                         BindingResult bindingResult,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }
            if (!beanValidator(result, bindingResult)) {
                return result;
            }

            Date now = new Date();

            int userId = Principal.getCurrent().getId();
            param.setUpdateBy(userId);
            param.setUpdateDate(now);
            this.paramService.saveOne(param);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }

    @ResponseBody
    @RequiresPermissions("sys:param:delete")
    @RequestMapping(value = "/delete", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
    public Object delete(@RequestParam("id") int paramId,
                         HttpServletRequest request) {
        JsonResult result = JsonResult.create();
        try {
            if (!checkCaptcha(request, result, false)) {
                return result;
            }

            this.paramService.deleteOneById(paramId);
        } catch (GenesisException ex) {
            result.error(ex.getMessage());
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            result.error();
        }

        return result;
    }
}
